package guice.boot.archive.container.registry;

import com.sun.istack.internal.NotNull;
import guice.boot.archive.spi.registry.*;

/**
 * Filter Service according to the given {@linkplain ServiceProvider}
 */
public class ServiceFilterImpl<T> implements ServiceFilter<T> {

    private ServiceProviderType serviceProviderType;

    private Class<?> serviceInterface;

    private String uniqueId;

    @Override
    public boolean match(@NotNull ServiceReference serviceReference) {
        ServiceMetaData serviceMetadata = serviceReference.getServiceMetaData();
        ServiceProvider serviceProvider = serviceMetadata.getServiceProvider();

        boolean isMatch = matchUniqueId(serviceMetadata.getUniqueId());//
        isMatch &= matchProviderType(serviceProvider.getServiceProviderType());//
        isMatch &= matchServiceInterface(serviceMetadata.getServiceInterfaceClass());
        return isMatch;
    }

    private boolean matchUniqueId(String uniqueId) {
        if (this.uniqueId == null) {
            return true;
        }
        return this.uniqueId.equals(uniqueId);
    }


    private boolean matchServiceInterface(Class serviceInterface) {
        if (this.serviceInterface == null) {
            return true;
        }
        return this.serviceInterface.equals(serviceInterface);
    }

    private boolean matchProviderType(ServiceProviderType serviceProviderType) {
        if (this.serviceProviderType == null) {
            return true;
        }
        return this.serviceProviderType.equals(serviceProviderType);
    }

    public ServiceProviderType getServiceProviderType() {
        return serviceProviderType;
    }

    public ServiceFilterImpl setServiceProviderType(ServiceProviderType serviceProviderType) {
        this.serviceProviderType = serviceProviderType;
        return this;
    }

    public Class<?> getServiceInterface() {
        return serviceInterface;
    }

    public ServiceFilterImpl setServiceInterface(Class<?> serviceInterface) {
        this.serviceInterface = serviceInterface;
        return this;
    }

    public String getUniqueId() {
        return uniqueId;
    }

    public ServiceFilterImpl setUniqueId(String uniqueId) {
        this.uniqueId = uniqueId;
        return this;
    }
}